﻿using HomagGroup.Base.UI;
using HomagGroup.Base.UI.Controls;
using HomagGroup.Base.UI.Themes.Resources;
using HomagChina.CCT.BaseUI.DataModel;
using System;

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

using static HomagChina.CCT.BaseUI.ProcessResourceInternal;
using localText = HomagChina.Basic.CCT.ResourceLibrary.Properties.Resources;
using HomagChina.CCT.BaseUI.ViewModel;
using HomagChina.CCT.BaseUI.Views;

namespace HomagChina.CCT.BaseUI
{
    public class HomeViewModel : HomagGroup.Base.UI.NotifyPropertyChangedBase
    {
        #region Command

        public RelayCommand ActionButtoClick { get; }
        public RelayCommand ClickInFeed { get; }
        public RelayCommand ClickOutFeed { get; }
        public RelayCommand ClickCancelAll { get; }
        public RelayCommand ClickRunEmpty { get; }
        public RelayCommand EditCommand { get; }
        public RelayCommand DeleteCommand { get; }
        public RelayCommand OpenCommand { get; }
        public RelayCommand SearchCommand { get; }
        public RelayCommand UnLoadedCommand { get; }
        public RelayCommand LoadedCommand { get; }

        #endregion Command

        #region Conponents

        private int _TotalParts;

        public int TotalParts
        {
            get => _TotalParts;
            set { _TotalParts = value; OnPropertyChanged(); }
        }

        private CheckBoxButton _CheckBox_RunEmpty;

        public CheckBoxButton CheckBox_RunEmpty
        {
            get => _CheckBox_RunEmpty;
            set { _CheckBox_RunEmpty = value; OnPropertyChanged(); }
        }

        private bool _CB_REState;

        public bool CB_REState
        {
            get => _CB_REState;
            set { _CB_REState = value; OnPropertyChanged(); }
        }

        private DeviceState _InFeedState;

        public DeviceState InFeedState
        {
            get => _InFeedState;
            set { _InFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _OutFeedState;
        public string CurrentAdress { get; set; }

        public DeviceState OutFeedState
        {
            get => _OutFeedState;
            set { _OutFeedState = value; OnPropertyChanged(); }
        }

        private ObservableCollection<BoardInfoModel> list_BoardInfoModel;

        public ObservableCollection<BoardInfoModel> List_BoardInfoModel
        {
            get => list_BoardInfoModel;
            set { list_BoardInfoModel = value; OnPropertyChanged(); }
        }

        private List<View_TransOnlineRecordsDetail> _list_TransOnLineModel;

        public List<View_TransOnlineRecordsDetail> list_TransOnLineModel
        {
            get => _list_TransOnLineModel;
            set { _list_TransOnLineModel = value; OnPropertyChanged(); }
        }

        public DropDownList dropDownList { get; set; }

        #region ToggleSwitch

        private bool _InFeedCheck;

        public bool InFeedCheck
        {
            get => _InFeedCheck;
            set { _InFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _InFeedEnable = true;

        public bool InFeedEnable
        {
            get => _InFeedEnable;
            set { _InFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _OutFeedCheck;

        public bool OutFeedCheck
        {
            get => _OutFeedCheck;
            set { _OutFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _OutFeedEnable = true;

        public bool OutFeedEnable
        {
            get => _OutFeedEnable;
            set { _OutFeedEnable = value; OnPropertyChanged(); }
        }

        #endregion ToggleSwitch

        private bool _RunEmptyCheck;

        public bool RunEmptyCheck
        {
            get => _RunEmptyCheck;
            set { _RunEmptyCheck = value; OnPropertyChanged(); }
        }

        private Canvas _BoardsCanvasView = new Canvas();

        public Canvas BoardsCanvasView
        { get => _BoardsCanvasView; set { _BoardsCanvasView = value; OnPropertyChanged(); } }

        /// <summary>
        /// Dropdown list
        /// </summary>
        public object SelectedValue;

        #region 属性

        private Canvas _warehouse;

        public Canvas Warehouse
        {
            get => _warehouse;
            set { _warehouse = value; OnPropertyChanged(); }
        }

        private Canvas _lead;

        public Canvas Lead
        {
            get => _lead;
            set { _lead = value; OnPropertyChanged(); }
        }

        public Dictionary<string, StorageDataModel> StorageDataModels = new Dictionary<string, StorageDataModel>();

        #endregion 属性

        #endregion Conponents

        #region Handle

        //private CommonHandle Handle_Common;
        //private InsertInfoHandle Handle_Insert;
        //private SearchInfoHandle Handle_Search;
        //private DeleteInfoHandle Handle_Delete;
        //private RunEmptyHandle Handle_RunEmpty;

        #endregion Handle

        private DispatcherTimer UpdateSessionTimer;

        public HomeViewModel()
        {
            ClickInFeed = new RelayCommand(ClickInFeedCommand);
            ActionButtoClick = new RelayCommand(ActionButtoClickCommand);
            ClickOutFeed = new RelayCommand(ClickOutFeedCommand);
            ClickCancelAll = new RelayCommand(ClickCancelAllCommand);
            ClickRunEmpty = new RelayCommand(ClickRunEmptyCommand);
            EditCommand = new RelayCommand(EditBoardInfo);
            DeleteCommand = new RelayCommand(DeleteBoardInfo);
            OpenCommand = new RelayCommand(OpenDailyCounterDialog);
            LoadedCommand = new RelayCommand(ViewloadedCommand);
            UnLoadedCommand = new RelayCommand(ViewUnloadedCommand);

            //Handle_Common = new CommonHandle();
            //Handle_Insert = new InsertInfoHandle();
            //Handle_Search = new SearchInfoHandle();
            //Handle_Delete = new DeleteInfoHandle();
            //Handle_RunEmpty = new RunEmptyHandle();
            LoadDropDownList();
            Warehouse = new Canvas();
            CreateCanvas();
            UpdateSessionTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(1500)
            };
        }

        /// <summary>
        ///
        /// </summary>
        private void ViewloadedCommand()
        {
            Refresh();
        }

        /// <summary>
        /// Unloaded
        ///
        /// </summary>
        private void ViewUnloadedCommand()
        {
            UpdateSessionTimer.Stop();
        }

        public void Refresh()
        {
            UpdateSessionTimer.Tick += (sender, args) =>
            {
                //List_BoardInfoModel = Handle_Search.GetTransOnLineInfo();//wcf
                //TotalParts = Handle_Search.GetTotalPartsCount();
                BoardsCanvasView.Children.Clear();
                Warehouse.Children.Remove(BoardsCanvasView);
                if (List_BoardInfoModel != null)
                {
                    foreach (var item in List_BoardInfoModel)
                    {
                        if (item.Length != null && item.Width != null)
                        {
                            Rectangle rectangle = new Rectangle
                            {
                                Uid = item.Reference,
                                Width = (float)item.Length / 13,
                                Height = (float)item.Width / 12,
                                Fill = GetHexadecimalColor("#d5771e"),
                                ToolTip = new TextBlock()
                                {
                                    Text = "Reference:" + item.Reference + "\n"
                                        + "Length:" + item.Length + "\n"
                                        + "Width:" + item.Width + "\n"
                                        + "Thickness:" + item.Thickness,
                                    FontSize = 13,
                                    FontFamily = new FontFamily("Microsoft YaHei"),
                                    HorizontalAlignment = HorizontalAlignment.Center,
                                    VerticalAlignment = VerticalAlignment.Center
                                }
                            };
                            if (!item.Location.Equals("off"))
                            {
                                if (int.Parse(item.Location) > 100)
                                {
                                    rectangle.Opacity = 0.85;
                                }
                            }
                            Canvas.SetLeft(rectangle, (float)(item.PartsCoor_Left - rectangle.Width));
                            Canvas.SetTop(rectangle, (float)item.PartsCoor_Top);
                            Canvas.SetZIndex(rectangle, item.PartsCoor_ZIndex);
                            rectangle.MouseRightButtonDown += ModifyPlate;
                            BoardsCanvasView.Children.Add(rectangle);
                        }
                    }
                    Warehouse.Children.Add(BoardsCanvasView);
                }
            };

            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                UpdateSessionTimer.Start();
            }
        }

        #region Canvas

        /// <summary>
        ///
        /// </summary>
        public void CreateCanvas()
        {
            var locat = AppDomain.CurrentDomain.BaseDirectory;
            CreateImageCanvasView("s1", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 150, 650, 250, 80);
            CreateImageCanvasView("s2", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleySmall.png", 0, 158, 460, 250, 210);
            CreateImageCanvasView("s3", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 145, 310, 250, 170);
            CreateImageCanvasView("s4", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleyBig.png", 0, 150, 130, 250, 200);
            CreateImageCanvasView("H330", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H330.png", 0, 370, 65, 650, 330);
            //CreateImageCanvasView("s5", @"..\..\UIHelper\CanvasImage\SupplementaryRoller.png", 0, 980, 150, 80, 160);
            CreateImageCanvasView("s5", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H330-后加长.png", 0, 980, 130, 330, 200);
            CreateImageCanvasView("s6", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 1050, 310, 250, 170);
            CreateImageCanvasView("s7", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleySmall.png", 0, 1065, 460, 250, 210);
            CreateImageCanvasView("s100", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 1055, 650, 250, 80);
            CreateImageCanvasView("H230", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H230-L.png", 0, 370, 380, 750, 360);
            CreateSectionCanvasView();
        }

        /// <summary>
        /// 创建图片画布
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="imagePath"></param>
        /// <param name="strokeThickness"></param>
        /// <param name="left"></param>
        /// <param name="Top"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void CreateImageCanvasView(string Id, string imagePath, int strokeThickness, int left, int Top, int width, int height)
        {
            Rectangle ImageRectangle = new Rectangle
            {
                Uid = Id,
                Width = width,
                Height = height,
                Fill = CraeteImageBrushFill(imagePath),
                Stroke = Brushes.Black,
                StrokeThickness = strokeThickness,
            };

            StorageDataModels.Add(ImageRectangle.Uid, new StorageDataModel
            {
                Uid = ImageRectangle.Uid,
                Rectangle = ImageRectangle,
                Width = ImageRectangle.Width,
                Height = ImageRectangle.Height,
                Left = left,
                Top = Top,
            });
            ImageRectangle.MouseLeftButtonDown += AddPlate;
            Canvas.SetLeft(ImageRectangle, left);
            Canvas.SetTop(ImageRectangle, Top);
            Warehouse.Children.Add(ImageRectangle);
        }

        /// <summary>
        /// 创建点位画布
        /// </summary>
        public void CreateSectionCanvasView()
        {
            Canvas SectionCanvasView = new Canvas();
            //var LocationDetailInfo = Handle_Search.GetLocationDetailInfo(true);

            ActionButton actionButto = new ActionButton
            {
                Image = GetIconBrush(Icon.Refresh),
                IsLabelVisible = false,
                Command = ActionButtoClick
            };

            //foreach (var item in LocationDetailInfo)
            //{
            //    var grid = new Grid();
            //    Ellipse container = new Ellipse
            //    {
            //        Width = 45,
            //        Height = 45,
            //        Fill = Brushes.White,
            //        Stroke = Brushes.Green,
            //        StrokeThickness = 3,
            //    };

            //    TextBlock textBlock = new TextBlock
            //    {
            //        Text = item.Position,
            //        Foreground = Brushes.Green,
            //        Background = Brushes.White,
            //        FontSize = 17,
            //        FontWeight = FontWeights.Bold,
            //        HorizontalAlignment = HorizontalAlignment.Center,
            //        VerticalAlignment = VerticalAlignment.Center
            //    };
            //    grid.Children.Add(container);
            //    grid.Children.Add(textBlock);
            //    Canvas.SetLeft(grid, (float)item.ComponentsCoor_Left);
            //    Canvas.SetTop(grid, (float)item.ComponentsCoor_Top);
            //    Canvas.SetZIndex(grid, 100000);
            //    SectionCanvasView.Children.Add(grid);
            //}
            Warehouse.Children.Add(SectionCanvasView);
            Canvas.SetLeft(actionButto, 0);
            Canvas.SetTop(actionButto, 0);
            Canvas.SetZIndex(actionButto, 100000);
            Warehouse.Children.Add(actionButto);
        }

        private void ActionButtoClickCommand()
        {
            //Handle_Delete.DeleteOnLineRecords();
        }

        #endregion Canvas

        #region DropDownList

        /// <summary>
        /// 加载DropDownList内容
        /// Load the DropDownList
        /// </summary>
        public void LoadDropDownList()
        {
            dropDownList = new DropDownList();
            var Modes = new List<string>() { { "Auto" }, { "Manual" } };
            dropDownList.ItemsSource = (Modes);
            dropDownList.SelectedIndex = 0;
            dropDownList.SelectionChanged += DropDownList_SelectionChanged;
        }

        /// <summary>
        /// DropDownList 选择变化事件
        /// SelectionChanged of DropDownList
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DropDownList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            SelectedValue = ((DropDownList)sender).SelectedItem.ToString();
        }

        #endregion DropDownList

        #region Board

        /// <summary>
        /// 板件数据删除
        /// Delete the board information
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteBoardInfo(object obj)
        {
            if (HomagGroup.Base.UI.Windows.MessageBox.Show(localText.Are_you_sure_you_want_to_delete_this_Information, localText.Prompt_message, MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
            {
                BoardInfoModel BoardInfo = (BoardInfoModel)obj;
                //if (Handle_Delete.DeleteBoardInfoByUpi(BoardInfo.Reference))
                //{
                //    HomagGroup.Base.UI.Windows.MessageBox.Show(localText.Deleted_successfully);
                //}
            }
        }

        /// <summary>
        /// 板件数据编辑
        /// Edit the board information
        /// </summary>
        /// <param name="SelectItem"></param>
        private void EditBoardInfo(object SelectItem)
        {
            var SelectedItem = SelectItem as BoardInfoModel;
            if (SelectedItem != null)
            {
                HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(SelectedItem, true);
                UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
            }
        }

        /// <summary>
        /// 单击视图添加板件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddPlate(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CurrentAdress = ((Rectangle)sender).Uid;
            HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(null, false);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
        }

        private void ModifyPlate(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            BoardInfoModel boardInfoModel = null;
            boardInfoModel = List_BoardInfoModel.Where(s => s.Reference == ((Rectangle)sender).Uid).FirstOrDefault();
            HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(boardInfoModel, true);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="boardInfoModel"></param>
        public void AutomaticRunningBoards(float Length, float Width)
        {
            Rectangle rectangle = new Rectangle
            {
                Width = (double)Width / 10,
                Height = (double)Length / 10,
                Fill = GetHexadecimalColor("#d5771e"),
            };

            Canvas.SetLeft(rectangle, StorageDataModels[CurrentAdress].Left + StorageDataModels[CurrentAdress].Width - 50);
            Canvas.SetTop(rectangle, StorageDataModels[CurrentAdress].Top);
            Canvas.SetZIndex(rectangle, 10000);
            Warehouse.Children.Add(rectangle);
        }

        #endregion Board

        #region Infeed

        /// <summary>
        /// 入库功能开启
        /// Open the infeed function
        /// </summary>
        public void ClickInFeedCommand()
        {
            //if (this.InFeedCheck)
            //{
            //    ActivatedInfeed();
            //    if (!Utility.Globle.isInfeedAreaActive)
            //    {
            //        Utility.Globle.isInfeedAreaActive = true;
            //        //InfeedHandle infeedHandle = new InfeedHandle();
            //        //MachineHandle machineHandle = new MachineHandle();
            //    }
            //}
            //else
            //{
            //    UnactivatedInfeed();
            //}
        }

        public void ActivatedInfeed()
        {
            this.InFeedCheck = true;
            this.InFeedState = DeviceState.Ok;
            this.InFeedEnable = RunEmptyCheck ? false : true;
        }

        public void UnactivatedInfeed()
        {
            this.InFeedCheck = false;
            this.InFeedState = DeviceState.Off;
            this.InFeedEnable = RunEmptyCheck ? false : true;
            //Utility.Globle.isInfeedAreaActive = false;
        }

        #endregion Infeed

        #region Outfeed

        /// <summary>
        /// 出库功能开启
        /// Open the outfeed function
        /// </summary>
        public void ClickOutFeedCommand()
        {
            if (this.OutFeedCheck)
            {
                ActivatedOutfeed();
                //if (!Utility.Globle.isOutfeedAreaActive)
                //{
                //    //OutfeedHandle outfeedHandle = new OutfeedHandle();
                //    Utility.Globle.isOutfeedAreaActive = true;
                //}
            }
            else
            {
                UnactivatedOutfeed();
            }
        }

        public void ActivatedOutfeed()
        {
            this.OutFeedCheck = true;
            this.OutFeedState = DeviceState.Ok;
            this.OutFeedEnable = RunEmptyCheck ? false : true;
        }

        public void UnactivatedOutfeed()
        {
            this.OutFeedCheck = false;
            this.OutFeedState = DeviceState.Off;
            this.OutFeedEnable = RunEmptyCheck ? false : true;
            //Utility.Globle.isOutfeedAreaActive = false;
        }

        #endregion Outfeed

        #region Cancel All

        /// <summary>
        /// 取消所有功能点击事件
        /// Cancel all function
        /// </summary>
        public void ClickCancelAllCommand()
        {
            CancelAll();
        }

        /// <summary>
        /// 取消所有功能
        /// </summary>
        public void CancelAll()
        {
            UnactivatedRunEmpty();
            UnactivatedInfeed();
            UnactivatedOutfeed();
        }

        #endregion Cancel All

        #region Run Empty

        /// <summary>
        /// 清空线体所有板件
        /// Empty all the parts of the line
        /// </summary>
        public void ClickRunEmptyCommand()
        {
            ActivatedInfeed();
            ActivatedOutfeed();

            //if (RunEmptyCheck)
            //{
            //    Utility.Globle.isRunEmptyActive = true;
            //    Task.Factory.StartNew(async () =>
            //    {
            //        string callBackMsg = await Handle_RunEmpty.RunEmpty();
            //        CancelAll();
            //        HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(HomagChina.Basic.CCT.ResourceLibrary.Properties.Resources.ResourceManager, callBackMsg).ToString());
            //    });
            //}
            //else
            //{
            //    Utility.Globle.isRunEmptyActive = false;
            //}
        }

        /// <summary>
        ///
        /// </summary>
        public void UnactivatedRunEmpty()
        {
            RunEmptyCheck = false;
            //Utility.Globle.isRunEmptyActive = false;
        }

        #endregion Run Empty

        #region 统计编辑窗口

        /// <summary>
        /// 统计编辑窗口
        /// Edit window of count
        /// </summary>
        private void OpenDailyCounterDialog()
        {
            HomeDailyCounterDialogViewModel HomeDailyCounterDialogViewModel = new HomeDailyCounterDialogViewModel(null, false);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeDailyCounterDialog>(HomeDailyCounterDialogViewModel, null);
        }

        #endregion 统计编辑窗口
    }
}